package account
/**
处理消息
 */
import (
  "crypto/sha1"
  "encoding/hex"
  "encoding/xml"
  "gitee.com/yizhisamoye/GoWeChat/entity/msg"
  "sort"
  "strings"
)
//验证消息是否来自微信服务器
func (w WxAccount)VerifyMsg(signature,timestamp,nonce string)bool{
  token:=""
  if t,exist:=w.Options["token"];exist{
    token=t
  }
  tmpArr:=[]string{token,timestamp,nonce}
  sort.Strings(tmpArr)
  tmpStr:=strings.Join(tmpArr,"")
  h:=sha1.New()
  h.Write([]byte(tmpStr))
  sha1Str:=hex.EncodeToString(h.Sum(nil))
  if sha1Str==signature{
    return true
  }
  return false
}
//将微信返回的xml数据解析为对象
func parseMsgString(content string) (*msg.WxMsg, error) {
  return parseMsgBytes([]byte(content))
}
func parseMsgBytes(content []byte) (*msg.WxMsg, error) {
  result:=new(msg.WxMsg)
  err:=xml.Unmarshal(content,result)
  return result,err
}
//处理微信转发来的用户消息
func (w WxAccount)HandleMsg(content []byte)(string,error){
  if len(content)==0{
    return "",nil
  }
  m,err:=parseMsgBytes(content)
  if err!=nil{
    return "",err
  }
  if handleFunc,exist:=w.msgHandleFunc[m.MsgType];exist{
   respMsg,err:= handleFunc(m,content)
   if err!=nil{
     return "",err
   }
   if respMsg!=nil{
     return respMsg.ConvertToWxXml(),nil
   }
  }
  return "",nil
}
//根据消息类型设置handle方法
func(w *WxAccount)setMsgHandFunc(msgType string ,fn func(msg *msg.WxMsg,xmlContent []byte)(*msg.WxRespMsg,error))*WxAccount {
  msgType=strings.ToLower(msgType)
  w.msgHandleFunc[msgType]=fn
  return w
}
//设置文字类型事件消息处理方法
func(w *WxAccount)SetTextMsgHandleFunc(fn func(msg *msg.WxMsg,xmlContent []byte)(*msg.WxRespMsg,error))*WxAccount {
  return w.setMsgHandFunc("text",fn)
}
//设置图片类型事件消息处理方法
func(w *WxAccount)SetImageMsgHandleFunc(fn func(msg *msg.WxMsg,xmlContent []byte)(*msg.WxRespMsg,error))*WxAccount {
  return w.setMsgHandFunc("image",fn)
}
//设置声音类型事件消息处理方法
func(w *WxAccount)SetVoiceMsgHandleFunc(fn func(msg *msg.WxMsg,xmlContent []byte)(*msg.WxRespMsg,error))*WxAccount {
  return w.setMsgHandFunc("voice",fn)
}
//设置视频类型事件消息处理方法
func(w *WxAccount)SetVideoMsgHandleFunc(fn func(msg *msg.WxMsg,xmlContent []byte)(*msg.WxRespMsg,error))*WxAccount {
  return w.setMsgHandFunc("video",fn)
}
//设置短视频类型事件消息处理方法
func(w *WxAccount)SetShortVideoMsgHandleFunc(fn func(msg *msg.WxMsg,xmlContent []byte)(*msg.WxRespMsg,error))*WxAccount {
  return w.setMsgHandFunc("shortvideo",fn)
}
//设置地理位置类型事件消息处理方法
func(w *WxAccount)SetLocationMsgHandleFunc(fn func(msg *msg.WxMsg,xmlContent []byte)(*msg.WxRespMsg,error))*WxAccount {
  return w.setMsgHandFunc("location",fn)
}

